package cn.hd01.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.hd01.repository.DictionaryRepository;
import cn.hd01.repository.entity.Dictionary;
import cn.hd01.service.DictionaryService;
import cn.hd01.util.DictionaryType;

@Service
public class DictServiceImpl extends BaseServiceImpl<Dictionary, Integer> implements DictionaryService {

	private DictionaryRepository repository;

	@Autowired
	public DictServiceImpl(DictionaryRepository repository) {
		super(repository);
		this.repository = repository;
	}

	@Override
	public Page<Dictionary> find(final Dictionary dict, Pageable pageable) {
		if (dict == null) {
			return repository.findAll(pageable);
		}

		return repository.findAll(Specifications.where(new Specification<Dictionary>() {
			@Override
			public Predicate toPredicate(Root<Dictionary> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<Predicate>();

				if (StringUtils.hasText(dict.getType())) {
					predicates.add(cb.equal(r.get("type").as(String.class), dict.getType()));
				}

				if (StringUtils.hasText(dict.getName())) {
					predicates.add(cb.like(r.get("name").as(String.class), "%" + dict.getName() + "%"));
				}

				return cb.and(predicates.toArray(new Predicate[] {}));
			}
		}), pageable);
	}
	
	@Override
	@CacheEvict(value="servant", key="#p0.name")
	public Dictionary save(Dictionary entity) {
		return repository.save(entity);
	}

    /**
     * 根据 type 获取字典，缓存过
     * @param type
     * @return
     */
	@Override
	@Cacheable(value="dict", key="#p0.name")
	public List<Dictionary> findByType(DictionaryType type) {
		return repository.findByType(type.getName());
	}
}
